package com.qili.service.supervisor.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qili.base.mapper.BaseMapper;
import com.qili.base.service.impl.BaseServiceImpl;
import com.qili.entity.affaircase.AffairCase;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.FileParse;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.supervisor.dto.SupervisorFileDTO;
import com.qili.exception.MyException;
import com.qili.mapper.supervisor.SupervisorFileMapper;
import com.qili.service.affairCase.AffairCaseService;
import com.qili.service.base.BaseDictService;
import com.qili.service.ela.ElasticSerachService;
import com.qili.service.supervisor.FileParseService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.supervisor.SupervisorProjectService;
import com.qili.util.*;
import com.spire.doc.Document;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.widget.PdfPageCollection;
import lombok.extern.java.Log;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Exceptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2020/11/2   文件名上传
 * @description
 */
@Log
@Service
public class SupervisorFileServiceImpl extends BaseServiceImpl<SupervisorFile, String> implements SupervisorFileService {

    @Autowired
    private SupervisorFileMapper supervisorFileMapper;
    @Autowired
    private BaseDictService baseDictService;
    @Autowired
    private UploadUtil uploadUtil;
    @Autowired
    private SupervisorProjectService projectService;
    @Autowired
    private FileParseService fileParseService;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    ElasticSerachService elasticSerachService;
    @Autowired
    AffairCaseService affairCaseService;


//    @Autowired
//    private SolrTemplate solrTemplate;

    @Override
    public BaseMapper<SupervisorFile, String> getMappser() {
        return supervisorFileMapper;
    }


    public JsonUtil addFile(SupervisorFile file) {
        JsonUtil j = new JsonUtil();


        try {
            supervisorFileMapper.insert(file);
            j.setFlag(true);
            j.setMsg("保存成功");
        } catch (MyException e) {
            j.setMsg("保存失败");
            j.setFlag(false);
            e.printStackTrace();
        }

        return j;

    }


    @Override
    public SupervisorFileDTO getPersonalImg(String projectId) {
        return (SupervisorFileDTO) supervisorFileMapper.getPersonalImg(projectId);
    }

    /**
     * @param ids
     * @Author:Zhangshuo
     * @Description:
     * @Date:20:52 2020-12-11
     */
    @Override
    public int deleteByProjectIds(String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            String proId = ids[i];
            SupervisorFile file = new SupervisorFile();
            file.setProjectId(proId);
            List<SupervisorFile> select = supervisorFileMapper.select(file);
            for (int j = 0; j < select.size(); j++) {
                String id = select.get(j).getId();
                // 删除Es 中的数据
//                deleteElacSearchData(id);
            }
        }
        int i1 = supervisorFileMapper.deleteByProjectIds(ids);
        return i1;
    }

    @Override
    public void deleteAffairCaseByProjectIds(String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            SupervisorFile deletefile = new SupervisorFile();
            deletefile.setProjectId(ids[i]);
            List<SupervisorFile> select = supervisorFileMapper.select(deletefile);
            for (int j = 0; j < select.size(); j++) {
                SupervisorFile supervisorFile = select.get(j);
                String id = supervisorFile.getId();
                AffairCase deleteaffairCase = new AffairCase();
                deleteaffairCase.setBusinessId(id);
                List<AffairCase> select1 = affairCaseService.select(deleteaffairCase);
                for (int k = 0; k < select1.size(); k++) {
                    AffairCase affairCase = select1.get(k);
                    // 为 无效
                    affairCase.setValid("0");
                    affairCase.setUpdateBy(CommonUtil.getUserId());
                    affairCase.setUpdateDate(DateUtil.getCurrentDateTime());
                    affairCaseService.updateByPrimaryKey(affairCase);
                }

            }

        }


    }


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 通过types
     * @Date:16:34 2020/12/15
     */
    @Override
    public List<SupervisorFileDTO> getFileCountByType(SupervisorFileDTO dto) {
        return supervisorFileMapper.getFileCountByType(dto);
    }

    @Override
    public List<SupervisorFileDTO> getFileCountByTypeZx(SupervisorFileDTO dto) {
        return supervisorFileMapper.getFileCountByTypeZx(dto);
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:
     * @Date:17:41 2020/12/17
     */
    @Override
    public List<SupervisorFileDTO> selectFileList(SupervisorFileDTO dto) {
        return supervisorFileMapper.selectFileList(dto);
    }


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:
     * @Date:17:41 2020/12/17
     */
    @Override
    public List<SupervisorFileDTO> selectFileListZx(SupervisorFileDTO dto) {
        return supervisorFileMapper.selectFileListZx(dto);
    }

    /**
     * @param fileId
     * @Author:zhaoyongke
     * @Description: 获取文件的上传方式
     * @Date:16:23 2021/1/14
     */
    public HashMap getOperByRole(String roleName, String fileId) throws Exception {
        HashMap map = new HashMap();
        String oper = "";
        SupervisorFile file = supervisorFileMapper.selectByPrimaryKey(fileId);
        String type = file.getType();
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtCode(type);
        baseDict.setBadtTypecode("WJ001");
        BaseDict base = baseDictService.select(baseDict).get(0);
        /*获取的文件的生成方式  1 表单模板 0 上传文件方式 */
        String level12 = base.getBadtLevel12();
        if (StringUtil.isNotBlank(level12)) {
            //String json = "[{\"xmjl\":[{\"oper\":\"'w,2'\"},{\"keyword\":\"山东正中信息技术股份有限公司\"}],\"zjl\":[{\"oper\":\"'ta,1'\"},{\"keyword\":\"总监理工程师签字\"}],\"jsfz\":[{\"oper\":\"'ta,1'\"},{\"keyword\":\"技术负责人签字\"}],\"yz\":[{\"oper\":\"'ta,1'\"},{\"keyword\":\"业主单位签字\"}]}]";
            /* 1 签字  2  盖章  W 关键字搜索方式（例如 监理规划 监理盖章位置不是表格） ta 为表格位置关键字 替换图片*/
            JSONObject jsonObject = (JSONObject) JSONArray.parseArray(level12).get(0);
            if (jsonObject.get(roleName) != null) {
                JSONArray jsonObjectArray = JSONArray.parseArray(jsonObject.get(roleName).toString());
                for (int i = 0; i < jsonObjectArray.size(); i++) {
                    JSONObject object = (JSONObject) jsonObjectArray.get(i);
                    if (i == 0) {
                        map.put("oper", object.get("oper"));
                    } else {
                        map.put("keyword", object.get("keyword"));
                    }
                }
            }
        }
        return map;
    }

    @Override
    public Integer selectOrderBySupervisorFile(Map paraMap) {
        return supervisorFileMapper.selectOrderBySupervisorFile(paraMap);
    }

    @Override
    public Integer selectMaxOrderBySupervisorFile(Map paraMap) {
        return supervisorFileMapper.selectMaxOrderBySupervisorFile(paraMap);
    }

    /**
     * 插入file表数据
     *
     * @param newSupervisorFile
     * @param baseDic           判断基准起点   例如:  /书著/2021_001_xxx书著
     *                          例如:   需要插入的表
     */
    @Override
    public void insertFile(SupervisorFile newSupervisorFile, SupervisorFile baseDic) {
        //当前文件路径
        String filePath = newSupervisorFile.getUrl().trim();

        //判断基准文件夹路径
        String baseDicPath = baseDic.getUrl().trim();

        if (StringUtils.isBlank(baseDicPath) || filePath.indexOf(baseDicPath) == -1) {
            throw new RuntimeException("插入文件时,当前文件路径" + filePath + "不包含基准判断文件路径" + baseDicPath);
        }
        String fileParentDicPath = filePath.substring(0, filePath.lastIndexOf(File.separator));
        //设置所涉及的文件夹(该方法执行以后,应该所有的上级目录都准备好了)
        String parentDicId = setFilePathDics(fileParentDicPath, baseDic, newSupervisorFile);
        newSupervisorFile.setSuperiorId(parentDicId);
        newSupervisorFile.setDealPath("2");
        insertSelective(newSupervisorFile);

    }


    /**
     * 设置文件涉及的所有文件夹
     * 该方法处理目标文件或文件夹
     *
     * @param targetFile 需要处理的文件:
     */
    public void setFilePathDics(SupervisorFile targetFile) {
        String targetFileUrl = targetFile.getUrl();
        File targetFileOs = new File(targetFileUrl);
        targetFileUrl = targetFileOs.getPath();
        log.info("****对文件(url:" + targetFile.getUrl() + ",fileName:" + targetFile.getFileName() + ")进行处理");
        if (StringUtils.isBlank(targetFileUrl)) {
            log.warning("设置文件/文件夹的相关路径时,参数对象的url为空!(id:)" + targetFile.getId());
            return;
        }
        if (StringUtils.isNotBlank(targetFile.getSuperiorId())) {
            log.info("该文件已经设置过");
        } else {
            if (targetFileOs.exists()) {
                //如果是文件,去上一级的目录路径
                targetFileUrl = targetFileOs.getParentFile().getPath();
                SupervisorFile baseFile = new SupervisorFile();
                String baseFilePath = uploadUtil.getUploadPath();
                //因为数据库存储目录的url是最后不带斜杠的
                if (baseFilePath.endsWith(File.separator)) {
                    baseFilePath = baseFilePath.substring(0, baseFilePath.length() - 1);
                }
                File baseFileOs = new File(baseFilePath);
                baseFilePath = baseFileOs.getPath();
                baseFile.setUrl(baseFilePath);
                List<SupervisorFile> select = select(baseFile);
                if (CollectionUtil.isEmpty(select)) {
                    throw new RuntimeException("没有设置基本文件夹");
                }
                String projectId = targetFile.getProjectId();
                String s = "";
                SupervisorProject supervisorProject = null;
                if (StringUtils.isNotBlank(projectId)) {
                    supervisorProject = projectService.selectByPrimaryKey(projectId);

                }
                if (supervisorProject != null) {
                    s = setFilePathDicsBase(targetFileUrl, select.get(0), projectId);
                } else {
                    s = setFilePathDicsBase(targetFileUrl, select.get(0), "");
                }
                targetFile.setSuperiorId(s);
                if (StringUtils.isBlank(targetFile.getZskfileType())) {
                    targetFile.setZskfileType("2");
                }
                targetFile.setDeleteState("1");
                // 根据 superior_id 查询
                SupervisorFile tempFile = supervisorFileMapper.selectByPrimaryKey(targetFile.getSuperiorId());
                // 保存path_key
                String key = tempFile.getPathKey() + "," + targetFile.getId();
                targetFile.setPathKey(key);
                updateByPrimaryKeySelective(targetFile);
            } else {
                log.warning("该数据对应的操作系统文件不存在");
            }
            log.info("********一条数据处理完成*********");
        }
    }

    /**
     * 设置文件涉及的所有文件夹
     *
     * @param targetDicPath 需要创建的最终文件夹
     * @param baseFile      截取的基本文件夹路径
     */
    public String setFilePathDicsBase(String targetDicPath, SupervisorFile baseFile, String projectId) {
        //不带斜杠的基准路径
        String baseUrl = baseFile.getUrl();
        if (StringUtils.isNotBlank(targetDicPath) && baseFile.getUrl().equals(targetDicPath)) {
            return baseFile.getId();
        }
        if (baseUrl.endsWith(File.separator)) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        String backDics = targetDicPath.substring(baseUrl.length() + 1);
        String separator = "/|\\\\";
        String[] split = backDics.split(separator);
        String fileId = baseFile.getId();
        for (int i = 0; i < split.length; i++) {
            if (StringUtils.isNotBlank(split[i])) {
                String aFileUrl = "";
                if (baseUrl.endsWith(File.separator)) {
                    aFileUrl = baseUrl + split[i];
                } else {
                    aFileUrl = baseUrl + File.separator + split[i];
                }
                File aFileOs = new File(aFileUrl);
                aFileUrl = aFileOs.getPath();
                SupervisorFile selectFile = new SupervisorFile();
                selectFile.setUrl(aFileUrl);
                List<SupervisorFile> select = select(selectFile);
                if (CollectionUtil.isEmpty(select)) {
                    //表中没有数据:
                    try {
                        String userId = CommonUtil.getUserId();
                        selectFile.setCreateBy(userId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    selectFile.setSuperiorId(baseFile.getId());
                    selectFile.setDeleteState("1");
                    selectFile.setZskfileType("1");
                    selectFile.setFileName(split[i]);
                    selectFile.setCreateDate(new Date());
                    selectFile.setExamineUser(baseFile.getExamineUser());
                    selectFile.setDownloadUser(baseFile.getDownloadUser());
                    selectFile.setCanotSeeRoles(baseFile.getCanotSeeRoles());
                    //如果projectId是项目id，设置上：
                    if (StringUtils.isNotBlank(projectId)) {
                        selectFile.setProjectId(projectId);
                    }
                    insertSelective(selectFile);
                    baseUrl = aFileUrl;
                    baseFile = selectFile;
                    fileId = selectFile.getId();
                } else {
                    String url = select.get(0).getUrl();
                    File urlFile = new File(url);
                    baseUrl = urlFile.getPath();
                    baseFile = select.get(0);
                    fileId = select.get(0).getId();
                }
            }
        }
        return fileId;
    }

    /**
     * 设置文件涉及的所有文件夹
     *
     * @param targetDicPath 需要创建的最终文件夹
     * @param baseFile      截取的基本文件夹路径
     */
    public String setFilePathDics(String targetDicPath, SupervisorFile baseFile, SupervisorFile newFile) {
        String baseUrl = baseFile.getUrl();
        File baseFileOs = new File(baseUrl);
        baseUrl = baseFileOs.getPath();
        if (baseUrl.equals(targetDicPath)) {
            //这里是正中参编标准类型表单:
            return baseFile.getId();
        }
        String backDics = targetDicPath.substring(baseUrl.length() + 1);
        String fileName = targetDicPath.substring(targetDicPath.lastIndexOf(File.separator) + 1);
        String separator = "/|\\\\";
        String[] split = backDics.split(separator);
        String fileId = "";
        for (int i = 0; i < split.length; i++) {
            String aFileUrl = "";
            if (baseUrl.endsWith(File.separator)) {
                aFileUrl = baseUrl + split[i];
            } else {
                aFileUrl = baseUrl + File.separator + split[i];
            }
            File aFileUrlOs = new File(aFileUrl);
            aFileUrl = aFileUrlOs.getPath();
            SupervisorFile selectFile = new SupervisorFile();
//            selectFile.setZskfileType("1");
            selectFile.setUrl(aFileUrl);
//            selectFile.setSuperiorId(baseFile.getId());
            if (StringUtils.isNotBlank(newFile.getType())) {
                selectFile.setType(newFile.getType());
            }
            List<SupervisorFile> select = select(selectFile);
            if (CollectionUtil.isEmpty(select)) {
                //表中没有数据:
                try {
                    String userId = CommonUtil.getUserId();
                    selectFile.setCreateBy(userId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                selectFile.setDeleteState("1");
                selectFile.setZskfileType("1");
                selectFile.setFileName(split[i]);
                selectFile.setSuperiorId(baseFile.getId());
                selectFile.setCreateDate(new Date());
                selectFile.setExamineUser(baseFile.getExamineUser());
                if (StringUtils.isNotBlank(newFile.getLinkId())) {
                    selectFile.setLinkId(newFile.getLinkId());
                }
                selectFile.setDownloadUser(baseFile.getDownloadUser());
                selectFile.setCanotSeeRoles(baseFile.getCanotSeeRoles());
                insertSelective(selectFile);
                baseUrl = aFileUrl;
                baseFile = selectFile;
                fileId = selectFile.getId();
            }
            if (i == split.length - 1) {
                return fileId;
            }
        }
        if (split.length == 0) {
            fileId = baseFile.getId();
        }
        return fileId;
    }

    @Override
    public int insertSelective(SupervisorFile record) {
        //默认该文件/文件夹是没有删除的
        if (StringUtils.isBlank(record.getDeleteState())) {
            record.setDeleteState("1");
        }
        //如果没有设置知识库类型(文件/文件夹)那么默认文件
        if (StringUtils.isBlank(record.getZskfileType())) {
            record.setZskfileType("2");
        }

        if (StringUtils.isNotBlank(record.getUrl()) && (StringUtils.isBlank(record.getDealPath()) || !"2".equals(record.getDealPath()))) {
            File osFile = new File(record.getUrl());
            record.setUrl(osFile.getPath());
            if ("2".equals(record.getZskfileType())) {
                setFilePathDics(record);
            }
        }
        int i = super.insertSelective(record);
        // 根据 superior_id 查询
        SupervisorFile supervisorFile = supervisorFileMapper.selectByPrimaryKey(record.getSuperiorId());
        // 保存path_key
        String key = supervisorFile.getPathKey() + "," + record.getId();
        supervisorFileMapper.updatePathKeyById(record.getId(), key);
        // 解析文件  保存文本用于 智能检索

        try {
            parseFileToText(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * @param file
     * @Author:zhaoyongke
     * @Description: 解析文档 to  text
     * @Date:10:48 2021/5/31
     */
    @Override
    public void parseFileToText(SupervisorFile file) throws Exception {
        //13457363
        String content = "";
        if ("2".equals(file.getZskfileType())) {
            String url = file.getUrl();
            String fileType = file.getFileType();
            if (fileType.toLowerCase().equals(".doc") || fileType.toLowerCase().equals(".docx")) {
                Document doc = new Document();
                try {
                    FileInputStream fis = new FileInputStream(url);
                    System.out.println(fis.available());
                    if ((fis.available() / 1024 / 1024) < 5) {
                        doc.loadFromFile(url);
                        String text = doc.getText();
                        content = text;
                        saveParseFile(file.getId(), file.getFileName(), file.getSearchKey(), text);
                    } else {
                        saveParseFile(file.getId(), file.getFileName(), file.getSearchKey(), "");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    doc.close();
                }
            } else if (fileType.toLowerCase().equals(".pdf")) {
                PdfDocument doc = new PdfDocument();
                // pdf 解析
                try {
                    StringBuilder sb = new StringBuilder();
                    doc.loadFromFile(url);
                    PdfPageBase page = null;
                    for (int i = 0; i < doc.getPages().getCount(); i++) {
                        page = doc.getPages().get(i);
                        //调用extractText()方法提取文本
                        sb.append(page.extractText(true));
                    }
                    String ff = sb.toString().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
                    content = ff;
                    saveParseFile(file.getId(), file.getFileName(), file.getSearchKey(), ff);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    doc.close();
                }
            } else {
                saveParseFile(file.getId(), file.getFileName(), file.getSearchKey(), "");
            }
            try {
                // 保存到 elacsearch  20211008
                saveOrUpdateElacSearchData(file, content);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * @param file
     * @param content
     * @Author:zhaoyongke
     * @Description:
     * @Date:19:39 2021/10/7
     */
    public void saveOrUpdateElacSearchData(SupervisorFile file, String content) {
        try {
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            QueryBuilder queryBuilder = elasticSerachService.queryId(file.getId());
            boolBuilder.must(queryBuilder);
            SearchResponse searchResponse = elasticSerachService.searchMessage(boolBuilder, "", "", "");
            TotalHits totalHits = searchResponse.getHits().getTotalHits();
            Long total = totalHits.value;
            if (total > 0) {
                //更新操作
//                UpdateRequest updateRequest=new UpdateRequest("swordaa",file.getId());
//                Map<String, Object> jsonMap = new HashMap<>();
//                jsonMap.put("content",content);
//                jsonMap.put("fileName",file.getFileName());
//                jsonMap.put("searchKey",file.getSearchKey());
//                jsonMap.put("id",file.getId());
//                //updateRequest.doc(jsonMap);
//                UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
//                System.out.println(update.status());
            } else {
                // 保存 到elastaicsearch 中  2021 1006 增加
                IndexRequest indexRequest = new IndexRequest("swordaa");
                Map<String, Object> jsonMap = new HashMap<>();

                indexRequest.id(file.getId());
                jsonMap.put("id", file.getId());
//                jsonMap.put("content",content);
                jsonMap.put("fileName", file.getFileName());
                jsonMap.put("searchKey", file.getSearchKey());
                // 点赞人
                jsonMap.put("giveUser", "");
                // 点赞数量
                jsonMap.put("dznum", "");
                jsonMap.put("type", file.getType());
                jsonMap.put("createBy", file.getCreateBy());
                jsonMap.put("createUsername", "");
                jsonMap.put("url", file.getUrl());
                jsonMap.put("projectId", file.getProjectId());
                jsonMap.put("days", 0);
                jsonMap.put("hotnum", "");
                jsonMap.put("remark", file.getRemark());
                jsonMap.put("createDate", DateUtil.getCurrentDateNoSpliter());
                jsonMap.put("content", content);
                //
                // 查询角色
                String superiorId = file.getSuperiorId();
                SupervisorFile su = supervisorFileMapper.selectByPrimaryKey(superiorId);
                if (su != null) {
                    jsonMap.put("examineUser", su.getExamineUser());
                } else {
                    jsonMap.put("examineUser", "");
                }

                indexRequest.source(jsonMap);
                IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                if (index.getResult().name().equalsIgnoreCase("created")) {
                    System.out.println("创建成功");
                } else {
                    System.out.println("失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * @param fileId
     * @param text
     * @Author:zhaoyongke
     * @Description: 保存parseFile 文件
     * @Date:11:15 2021/5/31
     */
    @Override
    public void saveParseFile(String fileId, String fileName, String searchKey, String text) {
        FileParse fileParse = new FileParse();
        fileParse.setFileId(fileId);
        List<FileParse> select = fileParseService.select(fileParse);
        if (select.size() == 0) {
            fileParse.setContent(text);
            fileParse.setFileName(fileName);
            fileParse.setSearchKey(searchKey);
            fileParseService.insertSelective(fileParse);
        } else {
            //更新
            FileParse fileParseUpdate = select.get(0);
            fileParseUpdate.setContent(text);
            fileParseUpdate.setFileName(fileName);
            fileParseUpdate.setSearchKey(searchKey);
            fileParseUpdate.setModifyBy(CommonUtil.getUserId());
            fileParseUpdate.setModifyDate(DateUtil.getCurrentDateString());
            fileParseService.updateByPrimaryKey(fileParseUpdate);
        }
    }

    @Override
    public List<SupervisorFileDTO> getzxFileCountByType(SupervisorFileDTO dto) {
        return supervisorFileMapper.getzxFileCountByType(dto);
    }

    @Override
    public List<SupervisorFileDTO> getjcFileCountByType(SupervisorFileDTO dto) {
        return supervisorFileMapper.getjcFileCountByType(dto);
    }

    @Override
    public List<SupervisorFileDTO> getFileCountByTypeJc(SupervisorFileDTO dto) {
        return supervisorFileMapper.getFileCountByTypeJc(dto);
    }

    @Override
    public List<SupervisorFileDTO> selectFileListJc(SupervisorFileDTO dto) {
        return supervisorFileMapper.selectFileListJc(dto);
    }

    @Override
    public List<SupervisorFile> selectAllProjectFile() {
        return supervisorFileMapper.selectAllProjectFile();
    }

    @Override
    public List<SupervisorFileDTO> selectFileSerch(SupervisorFileDTO dto) {
        return supervisorFileMapper.selectFileSerch(dto);
    }

    //查询评论--智能检索
    @Override
    public List<SupervisorFileDTO> selectFileComment(SupervisorFileDTO dto) {
        return supervisorFileMapper.selectFileComment(dto);
    }

    //查询评论回复--智能检索
    @Override
    public List<SupervisorFileDTO> selectFileReply(SupervisorFileDTO dto) {
        return supervisorFileMapper.selectFileReply(dto);
    }

    //最佳实践库文档统计
    @Override
    public List<SupervisorFileDTO> showFileZjcgList(SupervisorFileDTO dto) {
        return supervisorFileMapper.showFileZjcgList(dto);
    }

    // 查询文件夹下的数量
    @Override
    public List<SupervisorFileDTO> showFileNumPic(SupervisorFileDTO dto) {
        return supervisorFileMapper.showFileNumPic(dto);
    }


    // 查询文件通过父级Id
    @Override
    public List<SupervisorFileDTO> showFileByParentId(SupervisorFileDTO dto) {
        return supervisorFileMapper.showFileByParentId(dto);
    }

    // 最佳实践库 人员统计
    @Override
    public List<SupervisorFileDTO> showFileByUserZj(SupervisorFileDTO dto) {
        return supervisorFileMapper.showFileByUserZj(dto);

    }


    @Override
    public List<SupervisorFileDTO> selectFileSeal(SupervisorFileDTO dto) {
        return supervisorFileMapper.queryFileSeal(dto);
    }

    @Override
    public List<SupervisorFileDTO> queryFileSealUrl(SupervisorFileDTO dto) {
        return supervisorFileMapper.queryFileSealUrl(dto);
    }

    @Override
    public List<SupervisorFileDTO> querySerachFileList(SupervisorFileDTO dto) {
        return supervisorFileMapper.querySerachFileList(dto);
    }

    public int deleteByPrimaryKey(String id) {
        int i = supervisorFileMapper.deleteByPrimaryKey(id);
        return i;
    }


    /**
     * @param id
     * @Author:zhaoyongke
     * @Description: 删除Es 中的数据
     * @Date:14:30 2022/5/24
     */
    public void deleteElacSearchData(String id) {
        try {
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            QueryBuilder queryBuilder = elasticSerachService.queryId(id);
            boolBuilder.must(queryBuilder);
            SearchResponse searchResponse = elasticSerachService.searchMessage(boolBuilder, "", "", "");
            TotalHits totalHits = searchResponse.getHits().getTotalHits();
            SearchHit[] hits = searchResponse.getHits().getHits();
            Long total = totalHits.value;
            if (total > 0) {
                // 删除
                for (int i = 0; i < hits.length; i++) {
                    elasticSerachService.deleteById(hits[i].getId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
   public  List<SupervisorFileDTO> queryBigMall(SupervisorFileDTO dto){
      return   supervisorFileMapper.queryBigMall(dto);
    }


}
